package com.hfzy.ihk.web.freeswitchCall.support.freeswitch.handler;


import com.alibaba.fastjson.JSONObject;
import com.hfzy.ihk.common.support.againtask.DelayQueueManager;
import com.hfzy.ihk.common.support.againtask.DelayWorker;
import com.hfzy.ihk.facade.freeswitchCall.enums.CallTypeEnum;
import com.hfzy.ihk.facade.freeswitchCall.enums.MsgTypeEnum;
import com.hfzy.ihk.web.freeswitchCall.biz.PushDataToAnalysis;
import com.hfzy.ihk.web.freeswitchCall.biz.PushDataToEsBiz;
import com.hfzy.ihk.web.freeswitchCall.biz.PushDataToOracleBiz;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisFields;
import com.hfzy.ihk.web.freeswitchCall.constant.RedisKey;
import com.hfzy.ihk.web.freeswitchCall.context.BeanUtils;
import com.hfzy.ihk.web.freeswitchCall.support.freeswitch.base.AbstractRecordFileHandler;
import com.hfzy.ihk.web.freeswitchCall.support.freeswitch.event.FreeswitchRecordFileEvent;
import com.hfzy.ihk.web.freeswitchCall.vo.FreeswitchRecordFile;
import com.hfzy.ihk.web.freeswitchCall.vo.VoiceRTASRReportVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.core.task.TaskExecutor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * freeswitch 录音handler ,这个方法不需要了
 */
@Component
@Scope("prototype")
public class FreeswitchRecordFileHandler extends AbstractRecordFileHandler<FreeswitchRecordFile,FreeswitchRecordFileEvent> {

    Logger logger = LoggerFactory.getLogger(FreeswitchRecordFileHandler.class);

   /* @Value("${aliyun.bl-get-record-file-url}")
    private String blUrl;

    @Value("${bl.record-file-key}")
    private String key ;*/

    @Autowired
    PushDataToEsBiz fsPushDataToEsBiz;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    PushDataToOracleBiz pushDataToOracleBiz;

    @Resource
    TaskExecutor pushDataToOracleTaskExecutor;

    @Autowired
    PushDataToAnalysis pushDataToAnalysis;

    @Override
    protected String getRecordFileUrl(FreeswitchRecordFile data) {
        return data.getRecord_file();
    }

    @Override
    protected void dealData(FreeswitchRecordFile data, String recordFileUrl) {

        //通知语音分析服务那边本通通话结束
        pushEndToAnalyzeServer(data);

        //判断redis是否还存在该sessionId 的数据，如果存在先保存到redis 再推Es 因为可能存在呼叫记录还没推到ES 的情况，但是因为ES 的特性所以可以直接将录音推过去先
        Map<String,String> callHistoryMap = null;
        try {
            Boolean flag = redisTemplate.hasKey(RedisKey.CALL_HISTORY_RPIX + data.getOut_id());
            if (flag) {

                //写入到呼叫记录
                redisTemplate.opsForHash().put(RedisKey.CALL_HISTORY_RPIX + data.getOut_id(), RedisFields.CALL_HISTORY_RECORD_FILE_URL, recordFileUrl);

            }


        }catch (Exception e){
            logger.error(">>>>>>>>>>将录音文件写入redis 失败,sessionId:{},recordFileUrl:{}",data.getOut_id(),recordFileUrl,e);
        }
        //将需要推送到Es的录音sessionI和url保存到redis

       fsPushDataToEsBiz.setSessionIdToReids(data.getOut_id(),recordFileUrl);

        pushDataToOracleBiz.setSessionIdToReids(data.getOut_id());

        Map<String,String> map = new HashMap<>();
        map.put(RedisFields.CALL_HISTORY_SESSION_ID,data.getOut_id());
        map.put(RedisFields.CALL_HISTORY_RECORD_FILE_URL,recordFileUrl);
        map.put(RedisFields.CREATE_USER_ID,data.getCreateUserId());
        //推送录音到Hbase
        BeanUtils.getPushDataToHbaseBiz().pushDataToHbase(map);

    }


    /**
     * 通知语音分析服务那边本通通话结束,延迟10秒再发送
     * @param data
     */
    private void pushEndToAnalyzeServer(FreeswitchRecordFile data) {

        String[] packageIdAndCallTaskId = pushDataToAnalysis.readPackageIdAndCallTaskId(data.getOut_id());

        if(packageIdAndCallTaskId!=null&&packageIdAndCallTaskId.length>1) {


            logger.info("---------->10秒后将发送end消息到语音分析服务器");

            DelayWorker worker=new DelayWorker(3,1000,()->{


                logger.info("----->发送freeswitch通话结束状态到分析服务器packageIdAndCallTaskId：{}",packageIdAndCallTaskId);
                try {
                    pushDataToAnalysis.pushData(packageIdAndCallTaskId[0], packageIdAndCallTaskId[1], data.getOut_id(),  new VoiceRTASRReportVo(), CallTypeEnum.FREESWITCH_CALL.getValue(), MsgTypeEnum.END.getValue());
                }catch (Exception e){
                    logger.error("--------->发送freeswitch通话结束状态到分析服务器异常，sessionId:{}",data.getOut_id(),e);
                }
            });

            DelayQueueManager.getInstance().put(worker);
        }

    }

}
